package com.neu.dao;

import com.neu.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class BaseDao {
    private Connection conn;
    private PreparedStatement stmt;
    private ResultSet rst;

    protected final Connection getConnection()throws SQLException {
        return DBUtils.getConnection();
    }


    public static QueryRunner getQueryRunner(){
        return new QueryRunner(DBUtils.getDataSource());
    }
    //支持批处理的操作,使用同一条语句多次插入数据时,特别是从excel文件中导入数据时
    protected final int executeBatch(String sql,List<List<String>> list){
        int row=0;
        try {
           conn= getConnection();
            stmt=conn.prepareStatement(sql);
            if (list!=null){
                //获取要插入的每一行中的数据
                for (List<String> item:list){
                    //获取每一行中的每一个?号的值
                    for (int i=0;i<item.size();i++){
                        stmt.setObject(i+1,item.get(i));
                    }
                    //把该赋值后的sql添加批处理中,等待处理
                    stmt.addBatch();
                }
            }
            stmt.executeBatch();
            row=1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  row;
    }
}


